<template>
  <NuxtLayout name="userCenter">
    <div class="bg-gray-800 rounded-lg p-6">
      <h2 class="text-2xl font-bold text-white mb-6">个人中心</h2>

      <el-form
        ref="formRef"
        :model="userForm"
        :rules="rules"
        label-width="100px"
        class="max-w-2xl"
      >
        <el-form-item label="头像">
          <div class="flex items-center space-x-4">
            <el-avatar :src="userForm.avatar" :size="80">
              {{ userForm.nickName?.charAt(0) || 'U' }}
            </el-avatar>
            <el-upload
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              action="/dev-api/common/upload"
              :headers="uploadHeaders"
            >
              <el-button type="primary">更换头像</el-button>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item label="用户名">
          <el-input v-model="userForm.userName" disabled />
        </el-form-item>

        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="userForm.nickName" placeholder="请输入昵称" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item label="手机号" prop="phonenumber">
          <el-input v-model="userForm.phonenumber" placeholder="请输入手机号" />
        </el-form-item>

        <el-form-item label="性别">
          <el-radio-group v-model="userForm.sex">
            <el-radio value="0">男</el-radio>
            <el-radio value="1">女</el-radio>
            <el-radio value="2">保密</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">
            保存修改
          </el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="danger" @click="showPasswordDialog = true">
            修改密码
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 修改密码对话框 -->
      <el-dialog v-model="showPasswordDialog" title="修改密码" width="500px">
        <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="100px">
          <el-form-item label="旧密码" prop="oldPassword">
            <el-input v-model="passwordForm.oldPassword" type="password" show-password />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="passwordForm.newPassword" type="password" show-password />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showPasswordDialog = false">取消</el-button>
          <el-button type="primary" @click="updatePassword" :loading="passwordLoading">
            确定修改
          </el-button>
        </template>
      </el-dialog>
    </div>
  </NuxtLayout>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

definePageMeta({
  middleware: 'auth'
})

const userStore = useUserStore()
const formRef = ref<FormInstance>()
const passwordFormRef = ref<FormInstance>()
const loading = ref(false)
const passwordLoading = ref(false)
const showPasswordDialog = ref(false)

const uploadHeaders = computed(() => ({
  'Authorization': `Bearer ${userStore.token}`
}))

const userForm = reactive({
  userId: '',
  userName: '',
  nickName: '',
  email: '',
  phonenumber: '',
  sex: '2',
  avatar: ''
})

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const rules: FormRules = {
  nickName: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phonenumber: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

const validatePassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const passwordRules: FormRules = {
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validatePassword, trigger: 'blur' }
  ]
}

// 获取用户信息
const loadUserInfo = async () => {
  if (userStore.userInfo) {
    Object.assign(userForm, userStore.userInfo)
  } else {
    await userStore.getUserInfo()
    if (userStore.userInfo) {
      Object.assign(userForm, userStore.userInfo)
    }
  }
}

// 提交表单
const submitForm = async () => {
  const valid = await formRef.value?.validate()
  if (!valid) return

  loading.value = true
  try {
    await $fetch('/dev-api/system/user/profile', {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      },
      body: userForm
    })

    ElMessage.success('修改成功')
    await userStore.getUserInfo(true)
  } catch (error: any) {
    ElMessage.error(error.data?.msg || '修改失败')
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  loadUserInfo()
}

// 头像上传成功
const handleAvatarSuccess = (response: any) => {
  if (response.code === 200) {
    userForm.avatar = response.url
    ElMessage.success('头像上传成功')
  }
}

// 上传前验证
const beforeAvatarUpload = (file: any) => {
  const isImage = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片格式')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB')
    return false
  }
  return true
}

// 修改密码
const updatePassword = async () => {
  const valid = await passwordFormRef.value?.validate()
  if (!valid) return

  passwordLoading.value = true
  try {
    await $fetch('/dev-api/system/user/profile/updatePwd', {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      },
      body: passwordForm
    })

    ElMessage.success('密码修改成功，请重新登录')
    showPasswordDialog.value = false

    // 清空token并跳转到登录页
    await userStore.logout()
  } catch (error: any) {
    ElMessage.error(error.data?.msg || '密码修改失败')
  } finally {
    passwordLoading.value = false
  }
}

onMounted(() => {
  loadUserInfo()
})
</script>

<style scoped>
:deep(.el-form-item__label) {
  color: rgba(255, 255, 255, 0.8);
}

:deep(.el-input__wrapper) {
  background-color: rgba(31, 41, 55, 0.5);
}

:deep(.el-input__inner) {
  color: white;
}

:deep(.el-input.is-disabled .el-input__inner) {
  color: rgba(255, 255, 255, 0.5);
}
</style>